package com.heima.wemedia.service.Imp;
import java.sql.Wrapper;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.filter.WmTokenFilter;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImp extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;
    @Value("${file.oss.prefix}") //直接从配置中动态读取
    String prefix;
    @Value("${file.oss.web-site}") //直接从配置中动态读取
    String webSite;


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count > 0){
            CustException.cust( AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 删除素材库
        removeById(id);
        // 删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //1.参数校验
        dto.checkParam();
        //2.对数据进行条件查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //判断是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //对数据查询
        IPage<WmMaterial> iPage = page(page, wrapper);
        List<WmMaterial> records = iPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal());
        result.setData(records);
        return result;

    }

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile)  {
        //1.数据校验 校验数据是否为空
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"上传的文件不存在");
        }
        //1.1判断文件名是否符合规范
        String filename = multipartFile.getOriginalFilename();
        String type = filename.substring(filename.lastIndexOf("."));
        //对文件类型进行判断
        if (!checkFileSuffix(type)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文件类型不符合规范!");
        }
        //2.用户必须登录才能上传图片
        WmUser user = WmThreadLocalUtils.getUser();
        //判断是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未登录请先登录!");
        }
        //如果登录获取其中的id
        Integer id = user.getId();
        //创建对象设置id
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(id);
        //3.上传文件
        //参数一上传的文件夹
        //参数二 文件在文件夹的名称
        //参数三 要输入流
        //获得的是文件在oss中的完整路径
        String replace = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            String store  = fileStorageService.store(prefix, replace + type, multipartFile.getInputStream());
            //素材表添加一条数据
            wmMaterial.setUrl(store);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文件上传失败");
        }

        return ResponseResult.okResult();
    }

    /**
     * 判断文件格式是否符合
     * @param filename
     * @return
     */
    private boolean checkFileSuffix(String filename) {
        List<String> allowList = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        for (String allow : allowList) {
            if (allow.equals(filename)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 收藏取消
     * @param id
     * @return
     */
    @Override
    public ResponseResult addCancelCollect(Integer id,Short cancelCollectMaterial) {
        //校验数据
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"id不能为空");
        }
        //2.查询数据库中该素材的状态
        WmMaterial wmMaterial = getById(id);
        //3.判断这条数据是否存在
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获得token过滤出的登录的用户id
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //只允许修改自己的
        if(!wmMaterial.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }
        //4.数据存在修改状态码
        wmMaterial.setIsCollection(cancelCollectMaterial);
        //5.更新数据
        updateById(wmMaterial);

        return ResponseResult.okResult();
    }
}
